<template>
  <div class="simple-image-upload">
    <a-upload
      :file-list="fileList"
      name="image"
      list-type="picture-card"
      class="image-upload-list"
      :custom-request="customRequest"
      :before-upload="beforeUpload"
      :multiple="multiple"
      :max-count="multiple ? maxCount : 1"
      @change="handleChange"
      @remove="handleRemove"
      @preview="handlePreview"
    >
      <div v-if="fileList.length < (multiple ? maxCount : 1)" class="upload-button">
        <plus-outlined />
        <div style="margin-top: 8px">上传图片</div>
      </div>
    </a-upload>
    
    <!-- 预览模态框 -->
    <a-modal 
      :open="previewVisible" 
      :title="previewTitle" 
      :footer="null" 
      @cancel="handleCancel"
    >
      <img alt="preview" style="width: 100%" :src="previewImage" />
    </a-modal>
  </div>
</template>

<script setup lang="ts">
  import { ref, watch } from 'vue';
  import { PlusOutlined } from '@ant-design/icons-vue';
  import { message } from 'ant-design-vue';
  import Api from '@/api';
  import helper from '@/utils/helper';

  defineOptions({
    name: 'SimpleImageUpload',
  });

  interface Props {
    modelValue?: string;
    multiple?: boolean;
    maxCount?: number;
    maxSize?: number; // MB
  }

  const props = withDefaults(defineProps<Props>(), {
    modelValue: '',
    multiple: false,
    maxCount: 9,
    maxSize: 2,
  });

  const emit = defineEmits<{
    'update:modelValue': [value: string];
  }>();

  interface UploadFileType {
    uid: string;
    name: string;
    status: string;
    url?: string;
    thumbUrl?: string;
    md5?: string;
    response?: any;
  }

  const fileList = ref<UploadFileType[]>([]);
  const previewVisible = ref(false);
  const previewImage = ref('');
  const previewTitle = ref('');

  // 监听modelValue变化，初始化文件列表
  watch(
    () => props.modelValue,
    (newValue, oldValue) => {
      if (newValue && newValue !== oldValue) {
        // 处理多个MD5值（用逗号分隔）
        const md5Array = newValue.split(',').filter(md5 => md5.trim());
        const existingMd5s = fileList.value.map(f => f.md5);
        const newMd5s = md5Array.filter(md5 => !existingMd5s.includes(md5.trim()));
        
        // 如果有新的MD5值或者文件列表为空，重新创建文件列表
        if (newMd5s.length > 0 || fileList.value.length === 0) {
          fileList.value = md5Array.map((md5, index) => ({
            uid: `upload-${Date.now()}-${index}`,
            name: `image-${index + 1}.jpg`,
            status: 'done',
            url: helper.toApiUrl("file/download2?md5=" + md5),
            thumbUrl: helper.toApiUrl("file/download2?md5=" + md5),
            md5: md5.trim(),
            response: { md5: md5.trim() }
          }));
        }
      } else if (!newValue) {
        fileList.value = [];
      }
    },
    { immediate: true }
  );

  // 更新modelValue
  const updateModelValue = () => {
    const md5Values = fileList.value
      .filter(file => file.md5)
      .map(file => file.md5)
      .join(',');
    emit('update:modelValue', md5Values);
  };

  // 文件上传前的验证
  const beforeUpload = (file: File) => {
    const isImage = file.type.startsWith('image/');
    if (!isImage) {
      message.error('只能上传图片文件！');
      return false;
    }

    const isLtMaxSize = file.size / 1024 / 1024 < props.maxSize;
    if (!isLtMaxSize) {
      message.error(`图片大小不能超过 ${props.maxSize}MB！`);
      return false;
    }

    // 检查数量限制
    if (props.multiple && fileList.value.length >= props.maxCount) {
      message.error(`最多只能上传 ${props.maxCount} 张图片！`);
      return false;
    }

    return true;
  };

  // 上传图片
  const uploadImage = async (file: File) => {
    try {
      // 使用file.ts中封装的切片上传方法
      const result = await Api.file.uploadAvatar(file);
      
      if (result && result.md5) {
        return result;
      } else {
        throw new Error('上传失败');
      }
    } catch (error) {
      console.error('Image upload error:', error);
      throw error;
    }
  };

  // 自定义上传请求
  const customRequest = async (options: any) => {
    try {
      const hide = message.loading('图片上传中...', 0);
      const result = await uploadImage(options.file);
      hide();
      
      // 创建新的文件对象
      const newFile: UploadFileType = {
        uid: options.file.uid,
        name: options.file.name,
        status: 'done',
        url: helper.toApiUrl("file/download2?md5=" + result.md5),
        thumbUrl: helper.toApiUrl("file/download2?md5=" + result.md5),
        md5: result.md5,
        response: { md5: result.md5 }
      };

      // 根据是否支持多选来处理文件列表
      if (props.multiple) {
        // 多选模式：添加到文件列表
        fileList.value = [...fileList.value, newFile];
      } else {
        // 单选模式：替换文件列表
        fileList.value = [newFile];
      }
      
      updateModelValue();
      message.success('图片上传成功！');

      if (options.onSuccess) {
        options.onSuccess(result);
      }
    } catch (error) {
      message.error('图片上传失败');
      if (options.onError) {
        options.onError(error);
      }
    }
  };

  // 文件状态变化
  const handleChange = () => {
    // 文件状态变化处理
  };

  // 移除文件
  const handleRemove = (file: UploadFileType) => {
    // 从文件列表中移除指定文件
    fileList.value = fileList.value.filter(item => item.uid !== file.uid);
    updateModelValue();
    return true;
  };

  // 预览图片
  const handlePreview = async (file: UploadFileType) => {
    if (!file.url && !file.md5) {
      return;
    }
    previewImage.value = file.url || helper.toApiUrl("file/download2?md5=" + file.md5);
    previewVisible.value = true;
    previewTitle.value = '图片预览';
  };

  // 取消预览
  const handleCancel = () => {
    previewVisible.value = false;
    previewTitle.value = '';
  };
</script>

<style lang="less" scoped>
.simple-image-upload {
  .image-upload-list {
    :deep(.ant-upload-select-picture-card) {
      width: 104px;
      height: 104px;
      margin-right: 8px;
      margin-bottom: 8px;
    }

    :deep(.ant-upload-list-picture-card-container) {
      width: 104px;
      height: 104px;
      margin-right: 8px;
      margin-bottom: 8px;
    }
  }

  .upload-button {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 100%;
    color: #666;
    font-size: 14px;

    .anticon {
      font-size: 24px;
      margin-bottom: 8px;
    }
  }
}
</style> 